package com.dfzt.myutils.personal;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class WeatherUtil {
    private static final String BASE_URL = "https://api.caiyunapp.com/v2.6/";
    private static final String TOKEN = "a2OIEppDo2pub8Jv";
    private static final String LOCATION = "116.397477,39.908692";

    // 创建全局OkHttpClient实例（推荐复用）
    private static final OkHttpClient client = new OkHttpClient();

    public static String getWeather() throws IOException {
        String url = buildRequestUrl();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .addHeader("Accept", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败，状态码: " + response.code() +
                        "，响应信息: " + response.message());
            }

            if (response.body() == null) {
                throw new IOException("响应体为空");
            }

            return response.body().string();
        }
    }

    private static String buildRequestUrl() {
//        return BASE_URL + TOKEN + "/" + LOCATION + "/hourly?hourlysteps=48&dailysteps=7&alert=true";
        return "https://api.caiyunapp.com/v2.6/a2OIEppDo2pub8Jv/101.6656,39.2072/hourly?hourlysteps=48&begin=1742466905";
    }
    // 在WeatherUtil类中添加以下方法
    public static void writeToExcel(List<HourlyWeather> hourlyWeathers, String filePath) throws IOException {
        // 创建Excel工作簿
        try (Workbook workbook = new XSSFWorkbook()) { // 使用.xlsx格式
            Sheet sheet = workbook.createSheet("小时天气数据");

            // 创建表头样式
            CellStyle headerStyle = createHeaderStyle(workbook);

            // 创建表头行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"时间", "光照强度", "温度(℃)", "云量(%)", "风速(m/s)", "风向(度)"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 创建数据行
            int rowNum = 1;
            for (HourlyWeather weather : hourlyWeathers) {
                Row row = sheet.createRow(rowNum++);

                // 时间（格式化日期）
                Cell dateCell = row.createCell(0);

                // 如果需要日期格式化（添加日期处理）
                CreationHelper createHelper = workbook.getCreationHelper();
                CellStyle dateStyle = workbook.createCellStyle();
                dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd hh:mm"));
                // 在日期单元格设置样式
                dateCell.setCellStyle(dateStyle);

                dateCell.setCellValue(weather.getDatetime());

                // 光照强度
                row.createCell(1).setCellValue(weather.getLightIntensity());

                // 温度
                row.createCell(2).setCellValue(weather.getTemperature());

                // 云量（转换为百分比）
                row.createCell(3).setCellValue(weather.getCloudrate() * 100);

                // 风速
                row.createCell(4).setCellValue(weather.getWindSpeed());

                // 风向
                row.createCell(5).setCellValue(weather.getWindDirection());
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 写入文件
            try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
                workbook.write(outputStream);
            }
        }
    }

    // 创建表头样式
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(font);
        style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        return style;
    }

    // 使用示例
    public static void main(String[] args) {
        try {
            String weatherData = getWeather();
            System.out.println("获取天气数据成功：\n" + weatherData);

            // 如果需要解析JSON，可添加如下代码（需要Gson/Jackson依赖）
            List<HourlyWeather> hourlyWeathers = new WeatherParser().parse48HoursData(weatherData);
            // 添加表头
            System.out.println("\n时间                  | 温度(℃) | 云量(%) | 风速(m/s) | 风向(度)");
            System.out.println("---------------------------------------------------------------");
            for (HourlyWeather hourlyWeather : hourlyWeathers) {
                System.out.printf(
                        "%-20s | %7.1f | %7.1f | %9.1f | %8d%n",
                        hourlyWeather.getDatetime(),
                        hourlyWeather.getTemperature(),          // 温度保留1位小数
                        hourlyWeather.getCloudrate() * 100,      // 云量转为百分比
                        hourlyWeather.getWindSpeed(),
                        hourlyWeather.getWindDirection()
                );
            }

            // 将hourlyWeathers写入到excel中，表头是时间、温度、云量、风速、风向
            String excelPath = "weather_data.xlsx";
            writeToExcel(hourlyWeathers, excelPath);
            System.out.println("数据已成功写入：" + excelPath);

        } catch (IOException e) {
            System.err.println("获取天气数据失败: " + e.getMessage());
        }
    }

}
